//! Errors
use serde::Deserialize;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    // 网络错误
    // #[error("http error: {0}")]
    // Reqwest(#[from] reqwest::Error),
    /// OpenAI 调用错误
    #[error("{:?}: {}", .0.r#type, .0.message)]
    ApiError(ApiError),
    /// Error 序列化
    #[error("failed to deserialize api response: {0}")]
    JSONDeserialize(serde_json::Error),
    /// Error 文件保存
    #[error("failed to save file: {0}")]
    FileSaveError(String),
    /// Error 文件读取
    #[error("failed to read file: {0}")]
    FileReadError(String),
    /// Error on SSE streaming
    #[error("stream failed: {0}")]
    StreamError(String),
    /// Error
    #[error("invalid args: {0}")]
    InvalidArgument(String),
}

/// OpenAI API returns error object on failure
#[derive(Debug, Deserialize)]
pub struct ApiError {
    pub message: String,
    pub r#type: Option<String>,
    pub param: Option<serde_json::Value>,
    pub code: Option<serde_json::Value>,
}

/// Wrapper to deserialize the error object nested in "error" JSON key
#[derive(Debug, Deserialize)]
pub(crate) struct WrappedError {
    pub(crate) error: ApiError,
}

pub(crate) fn map_deserialization_error(e: serde_json::Error, bytes: &[u8]) -> Error {
    tracing::error!(
        "failed deserialization of: {}",
        String::from_utf8_lossy(bytes.as_ref())
    );
    Error::JSONDeserialize(e)
}
